import os
import glob
import yaml

class LoadFile:
    def __init__(self):
        self.home_config_path = os.path.join(os.environ.get('HOME', ''), '.config/compass-ci')
        # Glob for default YAML files
        self.default_files = glob.glob('/etc/compass-ci/defaults/*.yaml') + \
                    glob.glob(os.path.join(self.home_config_path, 'defaults', '*.yaml'))

    def load_one_yaml(self, file):
        """
        Load a single YAML file if it exists.
        Args:
            file (str): Path to the YAML file.
        Returns:
            dict: Parsed YAML content as a dictionary, or an empty dictionary if the file does not exist.
        """
        if not file or not os.path.exists(file):
            return {}

        with open(file, 'r') as f:
            try:
                return yaml.safe_load(f) or {}
            except yaml.YAMLError as e:
                print(f"Failed to load YAML file '{file}': {e}")
                return {}

    def load_my_config(self):
        """
        Load and merge configuration files from multiple locations.
        Returns:
        dict: A merged configuration dictionary.
        """
        config = {}
        if self.default_files:
            for file in self.default_files:
                config.update(self.load_one_yaml(file))

        # Determine lab configuration
        self.lab = os.environ.get('CCI_LAB', config.get('lab'))
        if self.lab:
            lab_file_paths = [
                os.path.join('/etc/compass-ci/include/lab', f"{self.lab}.yaml"),
                os.path.join(self.home_config_path, 'include/lab', f"{self.lab}.yaml")
            ]
            for file in lab_file_paths:
                config.update(self.load_one_yaml(file))

        return config
